package com.abe.libcore.view.common

import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.FragmentActivity
import com.abe.libquick.R
import java.lang.ref.WeakReference

object LoadDialog {
    private var dialog: AlertDialog? = null
    private var mActivity: WeakReference<FragmentActivity>? = null

    fun show(activity: FragmentActivity?) {
        if (activity == null) return
        mActivity = WeakReference(activity)
        activity.runOnUiThread {
            if (!activity.isFinishing) {
                val layout = LinearLayout(activity)
                layout.gravity = Gravity.CENTER
                layout.orientation = LinearLayout.VERTICAL
                layout.setPadding(0, 50, 0, 50)
                val progressBar = ProgressBar(activity)
                progressBar.isIndeterminate = true
                val loadTextView = TextView(activity)
                loadTextView.setGravity(Gravity.CENTER)
                val params = LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
                )
                params.setMargins(0, 20, 0, 0)
                layout.addView(progressBar)
                layout.addView(loadTextView, params)
                dialog = AlertDialog.Builder(activity)
                    .setView(layout)
                    .setCancelable(true).create()
                dialog = AlertDialog.Builder(activity).setView(progressBar).setMessage("Loading...")
                    .setCancelable(true).create()
                if (!dialog!!.isShowing) {
                    dialog!!.show()
                }
            }
        }
    }

    fun showBrief(activity: FragmentActivity?) {
        if (activity == null) return
        mActivity = WeakReference(activity)
        activity.runOnUiThread {
            if (!activity.isFinishing) {
                dialog = AlertDialog.Builder(activity, R.style.TransparentDialog).create()
                val view = LayoutInflater.from(activity).inflate(R.layout.progress_dialog_cus, null)
                dialog!!.setView(view)
                dialog!!.setCancelable(true)
                if (!dialog!!.isShowing) {
                    dialog!!.show()
                }
            }
        }
    }

    fun hide(act: FragmentActivity?) {
        var activity = act
        if (activity == null) {
            if (mActivity == null) {
                return
            }
            activity = mActivity!!.get()
        }
        if (activity == null) return
        activity.runOnUiThread {
            if (dialog != null && dialog!!.isShowing) {
                dialog!!.dismiss()
                dialog = null
            }
        }
    }
}